package com.syncshot.androidapp.activities;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.nineoldandroids.animation.ObjectAnimator;
import com.syncshot.androidapp.Constant;
import com.syncshot.androidapp.R;
import com.syncshot.androidapp.adapters.EfficientListAdapter;
import com.syncshot.androidapp.helper.WSHelper;
import com.syncshot.androidapp.helper.WSHelper.Call;
import com.syncshot.androidapp.helper.WSHelper.WebserviceCaller;
import com.syncshot.androidapp.helper.WSHelper.WebserviceCaller.WebserviceCallerListener;
import com.syncshot.androidapp.model.Event;
import com.syncshot.androidapp.model.User;
import com.syncshot.androidapp.util.WSUtil;
import com.syncshot.androidapp.viewholders.UsersViewHolder;

public class WaitingRoomActivity extends AbstractActivity implements WebserviceCallerListener {
	
	private GridView mGridView;
	private EfficientListAdapter<User> mAdpater;
	private List<User> mItemsList = new ArrayList<User>();
	private TextView mTTLTextView;
	private int mTtl;
	private boolean mIsOwner = false;
	private String mEventId;
	private BroadcastReceiver mUSerBroadcastReceiver;
	private BroadcastReceiver mTakePictureBroadcastReceiver;
	private String mUsername;
	private String mActionTime;

	
	private TextView mCamNumTextView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_waiting_room);
		
		mEventId = getIntent().getStringExtra(Constant.KEY_EVENT_ID);

        WebserviceCaller ws = new WebserviceCaller(this);
        ws.execute(WSUtil.generateCallEvent(mEventId));
		
		mUsername = getSharedPreferences(Constant.PREF, Context.MODE_PRIVATE).getString(Constant.PREF_USERNAME, "");
		
		WebserviceCaller wsusers = new WebserviceCaller(null);
		wsusers.execute(WSUtil.generateCallSubscribeToEvent(mEventId, mUsername));
		
		Toast.makeText(getApplicationContext(), mEventId, Toast.LENGTH_SHORT);
		
		mCamNumTextView = (TextView) findViewById(R.id.number_user_textview);
		
		if(getIntent().getStringExtra(Constant.KEY_EVENT_OWNER) != null
				&& getIntent().getStringExtra(Constant.KEY_EVENT_OWNER).equals(mUsername)){
			mIsOwner = true;
		}
		
		mTtl = getIntent().getIntExtra(Constant.KEY_EVENT_TTL, 30);
		
		final Time time = new Time(0, 0, mTtl);

		final SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
		
		mTTLTextView = (TextView) findViewById(R.id.ttlTextView);
		if(mIsOwner){
			mTTLTextView.setText(getString(R.string.take_shoot));
		} else {
			mTTLTextView.setText(sdf.format(new Date(time.getTime())));
		}

		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				mTtl--;
				final Time time = new Time(0, 0, mTtl);

				final SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						if(mIsOwner){
							mTTLTextView.setText(getString(R.string.take_shoot));
						} else {
							mTTLTextView.setText(sdf.format(new Date(time.getTime())));
						}
						
					}
				});
				if(mTtl == 0){
					this.cancel();
					
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							ObjectAnimator alpha = ObjectAnimator.ofFloat(mTTLTextView, "alpha", (float) 1.0, (float) 0.0);
							alpha.setRepeatCount(-1);
							alpha.setRepeatMode(0);
							alpha.setDuration(800);
							alpha.start();
							
						}
					});
					
					if(mIsOwner){
						takeTheShotClicked(null);
					}
					
					
				}
				
			}
		}, 1000, 1000);
		
		mGridView = (GridView) findViewById(R.id.gridView);
		mAdpater = new EfficientListAdapter<User>(this, R.layout.item_user, UsersViewHolder.class, mItemsList);
		mGridView.setAdapter(mAdpater);
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		updateUsersList();

		
		mUSerBroadcastReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				updateUsersList();
				
			}
		};
		
		registerReceiver(mUSerBroadcastReceiver, new IntentFilter(Constant.BROADCAST_NEW_USER));
		
		mTakePictureBroadcastReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				mActionTime = intent.getStringExtra(TakePictureActivity.KEY_TAKEPICT_TIMESTAMP);
				Intent actIntent = new Intent(WaitingRoomActivity.this, TakePictureActivity.class);
				actIntent.putExtra(Constant.KEY_EVENT_ID, mEventId);
				actIntent.putExtra(TakePictureActivity.KEY_TAKEPICT_TIMESTAMP, mActionTime);
				startActivity(actIntent);
				finish();
				
			}
		};
		
		registerReceiver(mTakePictureBroadcastReceiver, new IntentFilter(Constant.BROADCAST_TAKE_PICTURE));
		
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		if(mUSerBroadcastReceiver != null){
			unregisterReceiver(mUSerBroadcastReceiver);
		}
		
		if(mTakePictureBroadcastReceiver != null){
			unregisterReceiver(mTakePictureBroadcastReceiver);
		}
		
	}
	
	private void updateUsersList(){
		WebserviceCaller ws = new WebserviceCaller(this);
		ws.execute(WSUtil.generateCallUserList(mEventId));
	}

	@Override
	public void onResult(Call call, Object result) {
		if(result != null && result instanceof User[]){
			mItemsList.clear();
			User[] usersArray = (User[]) result;
			for(int i = 0 ; i < usersArray.length ; i++){
				mItemsList.add(usersArray[i]);
			}
			mCamNumTextView.setText("+"+mItemsList.size());
			mAdpater.notifyDataSetChanged();
		} else if(result instanceof Event) {
		    ((TextView) findViewById(R.id.project_event_textview)).setText(((Event)result).getDescription());
		}
		
	}
	
	public void takeTheShotClicked(View v){

		if(mIsOwner){
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					ObjectAnimator alpha = ObjectAnimator.ofFloat(mTTLTextView, "alpha", (float) 1.0, (float) 0.0);
					alpha.setRepeatCount(-1);
					alpha.setRepeatMode(0);
					alpha.setDuration(800);
					alpha.start();
					
				}
			});
			
			WebserviceCaller ws = new WebserviceCaller(this);
			ws.execute(WSUtil.generateCallTakeShot(mEventId));
			
		}
	}

}
